import {
  behavior as computedBehavior
} from "miniprogram-computed";
import {
  getBounceOffset,
  isCellEmpty,
  FormatDateTime,
  ConvertDateTime
} from "@/miniFile/utils/util"
import {
  getUserInfo,
  getMemberPower
} from "@/miniFile/config/product";
import {
  getFilePathByUrl
} from "@/miniFile/utils/file";
import {
  EVENT_BTN_CLICK
} from "./track"

/**
 * @处理团队日程元素
 * @param {*} item 
 */
const FormatTeamScheduleItem = (item, userId) => { 
  const startTime = FormatDateTime(item.customStart, "yyyy-MM-dd hh:mm");
  const endTime = FormatDateTime(item.customEnd, "yyyy-MM-dd hh:mm");
  const startDate = FormatDateTime(item.customStart, "yyyy/MM/dd hh:mm");
  const endDate = FormatDateTime(item.customEnd, "yyyy/MM/dd hh:mm");
  const start = FormatDateTime(item.customStart, "hh:mm");
  const end = FormatDateTime(item.customEnd, "hh:mm");
  const isToday = FormatDateTime(item.customStart, "yyyy/MM/dd") === FormatDateTime(item.customEnd, "yyyy/MM/dd");

  let reservationUsers = [];
  if (item.reservationInfo && item.reservationInfo.reservationUsers && item.reservationInfo.reservationUsers.length) {
    reservationUsers = item.reservationInfo.reservationUsers.map(itm => {
      if (itm.reserveStatus == 0) {
        itm.reserveStatusName = '待通过'
        itm.color = '#4097FF'
      } else if (itm.reserveStatus == 1) {
        itm.reserveStatusName = '预约通过'
        itm.color = '#52C41A'
      } else if (itm.reserveStatus == 2) {
        itm.reserveStatusName = '预约失败'
        itm.color = '#FF4D4F'
      } else if (itm.reserveStatus == 3) {
        itm.reserveStatusName = '已转介'
        itm.color = '#4097FF'
      } else if (itm.reserveStatus == 4) {
        itm.reserveStatusName = '未参加'
        itm.color = '#999'
      } else if (itm.reserveStatus == 5) {
        itm.reserveStatusName = '终止'
        itm.color = '#FF4D4F'
      }
      return {
        ...itm
      }
    })
  }

  return {
    id: item.id,
    contentId: item.contentId,
    reservationUsers: reservationUsers,
    scheduleType: item.scheduleType,
    content: item.content,
    place: item.place,
    customer: item.customer,
    contact: item.contact,
    researcherName: item.researcherName ? item.researcherName : "",
    managerName: item.reservationInfo ? item.reservationInfo.managerName : "",
    theme: item.reservationInfo ? item.reservationInfo.theme : "",
    startTime,
    endTime,
    start: start,
    end: end,
    startDate: startDate,
    endDate: endDate,
    customStart: item.customStart,
    customEnd: item.customEnd,
    isLock: item.lock,
    isMine: false,
    isToday
  }
}

/**
 * @处理日程管理元素
 * @param {*} item 
 */
const FormatMyScheduleItem = (item) => {
  const startDate = FormatDateTime(item.customStart, "yyyy/MM/dd hh:mm");
  const endDate = FormatDateTime(item.customEnd, "yyyy/MM/dd hh:mm");
  const start = FormatDateTime(item.customStart, "hh:mm");
  const end = FormatDateTime(item.customEnd, "hh:mm");
  const isToday = FormatDateTime(item.customStart, "yyyy/MM/dd") === FormatDateTime(item.customEnd, "yyyy/MM/dd");
  return {
    id: item.id,
    contentId: item.contentId,
    content: item.content,
    start: start,
    end: end,
    scheduleType: item.scheduleType,
    scheduleClassify: item.scheduleClassify,
    scheduleTag: item.scheduleTag || "",
    place: item.place,
    startDate: startDate,
    endDate: endDate,
    customer: item.customer,
    contact: item.contact,
    customStart: item.customStart,
    customEnd: item.customEnd,
    isLock: item.lock,
    isMine: true,
    isToday
  }
}

//根据时间获取星期
function getWeeks(day) {
  if (day == 7) {
    return '日'
  } else if (day == 1) {
    return '一';
  } else if (day == 2) {
    return '二';
  } else if (day == 3) {
    return '三';
  } else if (day == 4) {
    return '四';
  } else if (day == 5) {
    return '五';
  } else if (day == 6) {
    return '六';
  }
}

Component({
  behaviors: [computedBehavior],
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    isInit: false,

    paddingTop: 0,
    scrollHeight: 0,
    userInfo: {},
    powers: "",
    tipsMsg: false,

    //模式 schedule-日程 menu-事项
    mode: "schedule", 
    teamList: [],

    //更多日程显示
    richengShow: false,

    //日程明细显示
    ricshow: false,
    addrcinfo: {},
    
    //被选中的时间
    backDate: null,
    selectedTime: "",
    selectedDay: "",
    selectedDays: [],
    addTime: "",
    lockDay: [],
    riliList: [],

    scheduleScrollTop: 0,
    scheduleList: [],

    menuGroup: [],
    myMenuList: [],
    editFlag: false,
    editMyMenuList: [],

    noticeNums: 0,

    menuCountMap: {}, 
    totalCount: 0,
    groupExpandMap: {},

    tipType: "",
    tipMemo: "",

    expireVisible: false
  },

  computed: {
    isLogin(data) {
      const {
        userInfo
      } = data;

      let result = false;
      if (userInfo && !isCellEmpty(userInfo.id)) {
        result = true
      }

      return result;
    },
    scheduleFlag(data) {
      const {
        isLogin,
        mode
      } = data;

      if (isLogin) {
        return mode === "schedule"
      } else {
        return true;
      }
    },
    menuFlag(data) {
      const {
        isLogin,
        mode
      } = data;

      if (isLogin) {
        return mode === "menu"
      } else {
        return false;
      }
    },
    researcherIds(data) {
      const teamList = data.teamList;
      const result = [];

      teamList.forEach(item => {
        if (item.checked && item.fUserId != 0) {
          result.push(item.fUserId)
        }
      })

      return result;
    },
    researcherNames(data) {
      const teamList = data.teamList;
      const result = [];

      teamList.forEach(item => {
        if (item.checked && item.fUserId != 0) {
          result.push(item.fUserName)
        }
      })

      return result;
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onLoad(options) {
      this.initHeight();
      this.getRili(null, 1);
    },

    onShow() {
      this.initData();
    },

    /**
     * @初始化用户信息
     */
    initData: function () {
      this.initPower();
      this.initUser();
    },

    /**
     * @初始化用户
     */
    initUser: async function () {
      const res = await getUserInfo(true);

      console.log("当前用户信息：", res.userInfo);
      this.setData({
        userInfo: {
          ...res.userInfo,
          headportrait: res.userInfo.headportrait ? getFilePathByUrl(res.userInfo.headportrait) : 'https://www.finoview.com.cn/images/applet/userImage.jpg'
        }
      })

      if (res.status) {
        this.getMenuList();
        this.getMenuCount();
        this.getNoticeNums();
      } else {
        if (res.tipsFlag) {
          this.setData({
            tipsMsg: true
          })
        }
      }
      this.getData();
    },

    /**
     * @初始化权限
     */
    initPower: async function () {
      const res = await getMemberPower();

      this.setData({
        powers: res.powers
      }, () => {
        if (res.powers.indexOf("12-207") >= 0) {
          if(this.data.teamList.length === 0) {
            this.getResearcher();
          }
        }
      })
    },

    // 获取团队日程
    getResearcher() {
      EVENT_BTN_CLICK("日程tab", "团队日程");

      const app = getApp();
      var token = wx.getStorageSync('usertoken');
      app.reqFin({
        url: '/appletApi/schedule/getResearcher',
        method: 'post',
        header: {
          "token": token
        },
        data: {},
        success: (res) => {
          if (res.data.code == 1) {
            let teamList = []
            let allList = [{
              fUserName: '全部',
              fUserId: 0
            }]
            if (res.data.data && res.data.data.length > 0) {
              teamList = allList.concat(res.data.data)
            }

            teamList.forEach(teamItem => {
              teamItem.checked = true
            })

            this.setData({
              teamList: teamList
            });
          } else if (res.data.code == 3003) {
            this.setData({
              tipsMsg: true
            })
          }
        }
      });
    },

    handleTabChange() {
      this.setData({
        scheduleList: []
      }, () => {
        this.getData();
      })
    },

    /**
     * @获取数据
     */
    getData() {
      const scheduleComponent = this.selectComponent("#schedule");

      let type = "日程管理"
      if(scheduleComponent) {
        type = scheduleComponent.data.tabValue;
      }

      if(type === "日程管理") {
        this.getSchedule();
      } else if(type === "团队日程") {
        this.getTeamSchedule();
      }
    },

    /**
     * @获取日程管理
     */
    getSchedule() {
      this.setData({
        scheduleScrollTop: 0,
      });

      const app = getApp();
      var token = wx.getStorageSync('usertoken') || "";
      let header = {
        "Content-Type": "application/json"
      };
      if (token) {
        header["token"] = token;
      }
      var start = '';
      for (var i = 0; i < this.data.riliList.length; ++i) {
        if (this.data.riliList[i].checked == true) {
          start = this.data.riliList[i].key;
        }
      }
      var startTime = new Date(start.replace(/-/g, "/")).getTime();

      app.reqFin({
        url: '/appletApi/public/schedule/getMyScheduleList',
        method: 'post',
        header: header,
        timeout: 2500,
        data: {
          "startTime": startTime
        },
        success: (res) => {
          if (res.data.code === 1 && res.data.data && res.data.data.length) {
            const result = res.data.data.map(item => {
              return FormatMyScheduleItem(item);
            })

            this.setData({
              scheduleList: JSON.parse(JSON.stringify(result))
            })
          } else {
            this.setData({
              scheduleList: []
            })
          }
        },
        fail: () => {
          this.setData({
            scheduleList: []
          })
        },
        complete: () => {
          if(!this.data.isInit) {
            this.setData({ 
              isInit: true
            })
            if(this.data.scheduleList.length === 0) {
              this.setData({
                mode: "menu"
              })
            }
          }
        }
      });
    },

    /**
     * @获取团队日程
     */
    getTeamSchedule() {
      this.setData({
        scheduleScrollTop: 0,
      });

      const app = getApp();
      var token = wx.getStorageSync('usertoken') || "";
      let header = {
        "Content-Type": "application/json"
      };
      if (token) {
        header["token"] = token;
      }
      var start = '';
      for (var i = 0; i < this.data.riliList.length; ++i) {
        if (this.data.riliList[i].checked == true) {
          start = this.data.riliList[i].key;
        }
      }
      var startTime = new Date(start.replace(/-/g, "/")).getTime();
      const researcherIds = this.data.researcherIds;

      app.reqFin({
        url: '/appletApi/schedule/getTeamSchedule',
        method: 'post',
        header: header,
        timeout: 2500,
        data: {
          startTime: startTime,
          offset: 1,
          researcherIds: researcherIds
        },
        success: (res) => {
          if (res.data.code === 1 && res.data.data && res.data.data.length) {
            const result = res.data.data.map(item => {
              return FormatTeamScheduleItem(item, this.data.userInfo.userId);
            })

            this.setData({
              scheduleList: JSON.parse(JSON.stringify(result))
            })
          } else {
            this.setData({
              scheduleList: []
            })
          }
        },
        fail: () => {
          this.setData({
            scheduleList: []
          })
        },
        complete: () => {
          if(!this.data.isInit) {
            this.setData({ 
              isInit: true
            })
            if(this.data.scheduleList.length === 0) {
              this.setData({
                mode: "menu"
              })
            }
          }
        }
      });
    },

    /**
     * @获取菜单
     */
    getMenuList() {
      const app = getApp();
      const token = wx.getStorageSync('usertoken');

      app.reqZS({
        url: '/mine/menu/listByGroup',
        method: 'post',
        header: {
          "token": token
        },
        success: (res) => {
          console.log("当前菜单信息：", res);

          if (res.data.code === "10000") {
            const {
              allMenus,
              myMenus
            } = res.data.obj;
            this.setData({
              menuGroup: allMenus,
              myMenuList: myMenus
            })
          } else {
            this.setData({
              menuGroup: [],
              myMenuList: []
            })
          }
        },
        fail: () => {
          this.setData({
            menuGroup: [],
            myMenuList: []
          })
        }
      });
    },

    /**
     * @获取菜单待办数量
     */
    getMenuCount() {
      const app = getApp();
      const token = wx.getStorageSync('usertoken');

      app.reqZS({
        url: '/mine/menu/countsInfo',
        method: 'get',
        header: {
          "token": token
        },
        success: (res) => {
          if (res.data.code === "10000" && res.data.obj) {
            this.setData({
              menuCountMap: res.data.obj,
              totalCount: res.data.total 
            })
          } else {
            this.setData({
              menuCountMap: {},
              totalCount: 0
            })
          }
        },
        fail: () => {
          this.setData({
            menuCountMap: {},
            totalCount: 0
          })
        }
      });
    },

    /**
     * @获取消息提示数量
     */
    getNoticeNums() {
      const token = wx.getStorageSync('usertoken');
      const app = getApp();

      app.reqFin({
        url: '/appletApi/messageCenter/getUnread',
        method: 'post',
        header: {
          'Content-Type': 'application/json',
          'token': token
        },
        data: {

        },
        success: (res) => {
          if (res.data.code == 1) {
            this.setData({
              noticeNums: res.data.data
            })
          }
        }
      })
    },

    /**
     * @初始化高度
     */
    initHeight() {
      const height = 80;

      const {
        offsetTop
      } = getBounceOffset(height);

      this.setData({
        paddingTop: offsetTop + height
      })
    },

    /**
     * @点击日程前往页面
     * @param {*} e 
     */
    handleClickScheduleItem(e) {
      const item = e.detail;
      if (item.scheduleType === '2') {
        const authStatus = wx.getStorageSync('authStatus')
        if (authStatus == 0 && this.data.isLogin) {
          this.triggerEvent("onVerify");
          return;
        }

        let isLock = item.isLock;
        if (isLock == true || !this.data.isLogin) {
          wx.navigateTo({
            url: '/pages/meetDetail/index?id=' + item.contentId,
          })
        } else {
          this.triggerEvent("onTipsMsg");
        }
      } else if (item.scheduleType === '1') {
        const authStatus = wx.getStorageSync('authStatus')
        if (authStatus == 0 && this.data.isLogin) {
          this.triggerEvent("onVerify");
          return;
        }

        wx.navigateTo({
          url: '/pages/yuyueInfo/index?reservationId=' + item.contentId,
        })
      } else if (item.scheduleType === '0') {
        if(item.isMine) {
          var data = {
            start: item.start,
            end: item.end,
            content: item.content,
            place: item.place,
            userName: item.customer,
            userInfo: item.contact,
            id: item.id,
            customStart: item.customStart,
            customEnd: item.customEnd
          }
          wx.navigateTo({
            url: '/pages/myRichengInfo/index?richeng=' + JSON.stringify(data),
          })
        } else {
          const {
            content,
            place,
            customer,
            contact,
            researcherName
          } = item;

          const startDate = FormatDateTime(item.startTime, "yyyy年MM月dd日");
          const startTime = FormatDateTime(item.startTime, "hh:mm");
          const endDate = FormatDateTime(item.endTime, "yyyy年MM月dd日");
          const endTime = FormatDateTime(item.endTime, "hh:mm");

          const addrcinfo = {
            startDate,
            startTime,
            endDate,
            endTime,
            content,
            address: place,
            name: customer,
            contact,
            researcherName
          }

          this.setData({
            ricshow: true,
            addrcinfo: addrcinfo
          })

          wx.hideTabBar();
        }
      }
    },

    /**
     * @关闭日程弹框
     */
    handleCloseRichengDetail() {
      this.setData({
        ricshow: false
      })

      wx.showTabBar();
    },

    /**
     * @登录下点击头部两栏
     * @param {*} e 
     */
    handleClickMode(e) {
      const mode = e.detail;

      this.setData({
        mode
      }, () => {
        if(mode === "schedule") {
          this.handleTabChange();
        }
      })
    },

    /**
     * @点击日程
     */
    handleClickSchedule() {
      EVENT_BTN_CLICK("日程管理", "更多");

      this.setData({
        selectedDays: this.data.backDate ? [this.data.backDate] : this.data.selectedDays,
        richengShow: true
      });
      this.selectComponent("#calendar").refresh2(this.data.selectedDay);
    },

    // 关闭浮层
    handleCloseSchedule() {
      this.setData({
        richengShow: false
      });
      this.selectComponent("#calendar").refresh1(this.data.selectedDay);
      this.setData({
        selectedTime: ''
      });
    },

    /**
     * @点击菜单跳转
     * @param {*} menu 
     */
    handleClickMenuItem(e) {
      const menu = e.detail;
      const {
        groupName,
        name
      } = menu;

      EVENT_BTN_CLICK(groupName, name);

      const {
        path,
        redirectType,
      } = menu;

      switch (redirectType) {
        case "MINI":
          wx.navigateTo({
            url: path
          })
          break;
        case "MINI_TAB":
          wx.reLaunch({
            url: path
          })
          break;
        case "MINI_FN":
          this[path];
          break;
        case "WEB":
          const url = encodeURIComponent(path);
          wx.navigateTo({
            url: `/pages/topicDetail/index?src=${url}&withToken=1`,
          })
          break;
        default:
          break;
      }
    },

    /**
     * @收起展开我的菜单组
     * @param {*} e 
     */
    handleExpandMenuGroup(e) {
      const group = e.currentTarget.dataset.group;

      const groupExpandMap = this.data.groupExpandMap;

      groupExpandMap[group.groupId] = !groupExpandMap[group.groupId];

      this.setData({
        groupExpandMap
      })
    },

    /**
     * @保存编辑我的常用菜单
     */
    handleSaveMyMenu: async function (e) {
      const editMyMenuList = e.detail;
      const res = await this.saveMyMenuList(editMyMenuList);

      if (res.status) {
        this.setData({
          myMenuList: JSON.parse(JSON.stringify(editMyMenuList)),
        })
      } else {
        const message = res.message;
        wx.showToast({
          title: message,
          icon: "none"
        })
      }
      this.selectComponent("#menu").setData({
        editMyMenuList: [],
        editFlag: false
      })
    },

    /**
     * @保存编辑我的常用菜单
     */
    saveMyMenuList(editMyMenuList) {
      const ids = editMyMenuList.map(item => {
        return item.id;
      })

      return new Promise(resolve => {
        const app = getApp();
        const token = wx.getStorageSync('usertoken');

        app.reqZS({
          url: '/mine/menu/saveMyMenu',
          method: 'post',
          header: {
            "token": token
          },
          data: {
            ids: ids
          },
          success: (res) => {
            if (res.data.code === "10000") {
              resolve({
                status: true,
                message: ""
              })
            } else {
              resolve({
                status: false,
                message: res.data.msg ? res.data.msg : "保存失败"
              })
            }
          },
          fail: () => {
            resolve({
              status: false,
              message: "保存失败"
            })
          }
        });
      })
    },

    /** 
     * @点击提示日程管理
     */
    handleTipMySchedule() {
      const memo = `展示我录入的自有日程、预约/被预约的服务日程、我报名的会议日程、繁微上线的会议活动`;

      wx.hideTabBar();

      this.setData({
        tipType: "text",
        tipMemo: memo
      })
    },

    /**
     * @点击菜单右上角图标
     * @param {*} e 
     */
    handleTipMenuMemo(e) {
      const menu = e.detail;

      wx.hideTabBar();

      const {
        memo,
        memoType
      } = menu;

      this.setData({
        tipType: memoType,
        tipMemo: memo
      })
    },

    /**
     * @点击tab右上角图表
     * @param {*} e 
     */
    handleTipTabMemo(e) {
      wx.hideTabBar();

      const value = e.detail;
      let tipType = "text";
      let tipMemo = "";

      switch (value) {
        case "日程管理":
          tipMemo = `展示我录入的自有日程、预约/被预约的服务日程、我报名的会议日程、繁微上线的会议活动`;
          break;
        case "团队日程":
          tipMemo = `团队日程：以日期维度展示研究员服务信息\n访问权限：公司领导角色（查阅所有组）、组长角色（查阅本组）`;
          break;
        case "研究员日程":
          tipMemo = `研究员日程：以城市维度展示研究员服务信息\n访问权限：公司领导角色、研究员角色`;
          break;
      }

      this.setData({
        tipType,
        tipMemo
      })
    },

    /**
     * @关闭菜单提示
     */
    handleCloseTipMemo() {
      wx.showTabBar();

      this.setData({
        tipType: ""
      })
    },

    /**
     * @前往个人中心
     */
    handleGotoUser() {
      const {
        isLogin
      } = this.data;

      if (isLogin) {
        EVENT_BTN_CLICK("我的信息", "头像");

        wx.navigateTo({
          url: '/pages/personalCenter/index',
        })
      } else {
        EVENT_BTN_CLICK("我的信息", "登录");

        wx.navigateTo({
          url: '/pages/login/index',
        })
      }
    },

    /**
     * @点击有效期
     */
    handleClickExpire() {
      EVENT_BTN_CLICK("我的信息", "有效期");

      this.setData({
        expireVisible: true
      })
    },

    /**
     * @点击vip
     */
    handleClickVip() {
      EVENT_BTN_CLICK("我的信息", "VIP");

      const token = wx.getStorageSync('usertoken');
      const app = getApp();

      app.reqFin({
        url: '/appletApi/userCenter/getVipTips',
        method: 'post',
        header: {
          'Content-Type': 'application/json',
          'token': token
        },
        data: {},
        success: (res) => {
          if (res.data.code == 1) {
            let src = res.data.data
            wx.navigateTo({
              url: '/pages/topicDetail/index?src=' + encodeURIComponent(src) + '&withToken=1'
            })
          } else {
            wx.showToast({
              title: res.data.message,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    },

    /**
     * @点击前往繁微介绍
     */
    handleClickGuide() {
      const src = "https://www.finoview.com.cn/guidexcx"
      wx.navigateTo({
        url: '/pages/topicDetail/index?src=' + encodeURIComponent(src) + '&isGuidexcx=true'
      })
    },

    /**
     * @点击前往我的销售码
     */
    handleClickMyCode() {
      EVENT_BTN_CLICK("我的信息", "二维码");

      if (this.data.userInfo.recommendCode) {
        wx.navigateTo({
          url: '/pages/getcode/index?recommendCode=' + this.data.userInfo.recommendCode + "&level=" + this.data.userInfo.level + "&researcherId=" + this.data.userInfo.userId + "&fusername=" + this.data.userInfo.name,
        })
      } else {
        wx.showToast({
          title: '此用户无销售码！',
          icon: 'none',
          duration: 2000
        })
      }
    },

    /**
     * @点击团队日程研究员弹框
     */
    handleClickTeamShow() {
      this.setData({
        teamshow: true
      })

      wx.hideTabBar();
    },

    /**
     * @确认团队日程研究员弹框
     * @param {*} e 
     */
    handleConfirmTeamShow(e) {
      this.setData({
        teamshow: false
      })

      const teamList = e.detail;

      this.setData({
        teamList
      }, () => {
        this.getTeamSchedule();
      })
      setTimeout(() => {
        wx.showTabBar()
      }, 100)
    }, 

    /**
     * @关闭团队日程研究员弹框
     */
    handleCloseTeamShow() {
      this.setData({
        teamshow: false
      })
      setTimeout(() => {
        wx.showTabBar()
      }, 100)

    },

    /**
     * @点击前往我的消息
     */
    handleClickMessage() {
      EVENT_BTN_CLICK("我的信息", "通知");

      wx.navigateTo({
        url: '/pages/noticeMessage/index'
      })
    },

    /**
     * @关闭选择日程
     */
    handleCancelSchedule() {
      this.setData({
        richengShow: false
      });
      this.selectComponent("#calendar").refresh2(this.data.selectedDay);
      this.setData({
        selectedTime: ''
      });
    },

    /**
     * @确认选择日程
     */
    handleConfirmSchedule() {
      let time = ''
      if (this.data.backDate) {
        time = this.data.backDate
      } else {
        time = this.data.selectedTime;
      }
      if (this.data.selectedTime) {
        time = this.data.selectedTime
      } else {
        if (this.data.backDate) {
          time = this.data.backDate
        } else {
          time = this.data.selectedDay;
        }
      }
      // }
      this.setData({
        richengShow: false,
        addTime: time
      });
      this.getRili(time, 0);
      this.getData();
    },

    /**
     * @选择某个日期
     */
    handleSelectCalendarDay(e) {
      var list = this.data.riliList;
      for (var i = 0; i < list.length; ++i) {
        list[i].checked = false;
      }
      var index = e.detail.index;
      var item = this.data.riliList[index]; //每一个索引对应的内容
      item.checked = true;

      this.setData({
        selectedDay: item.key,
        riliList: this.data.riliList,
        addTime: e.detail.time
      }, () => {
        this.getData();
        this.selectComponent("#calendar").refresh2(item.key);
      });
    },

    /**
     * @返回当天
     */
    handleBackToday() {
      this.selectComponent("#calendar").backtoday();
    },

    /**
     * @锁定日期 ?
     * @param {*} e 
     */
    lockdays(e) {
      let lastMonthDays = e.detail.lastMonthDays
      let nextMonthDays = e.detail.nextMonthDays
      let lastMonth = []
      let nextMonth = []
      lastMonthDays.forEach(item => {
        lastMonth.push(item.year + '-' + item.m + '-' + item.date)
      })
      nextMonthDays.forEach(item => {
        nextMonth.push(item.year + '-' + item.m + '-' + item.day)
      })
      this.setData({
        lockday: lastMonth.concat(nextMonth)
      })
    },

    /**
     * @添加我的日程
     */
    handleAddSchedule() {
      wx.navigateTo({
        url: '/pages/myCalender/index?dateTime=' + this.data.selectedDay,
      })
    },

    /**
     * @点击日期时候触发的事件
     */
    getdate(e) {
      this.setData({
        selectedTime: e.detail.datestr,
      });
    },

    /**
     * @获取日历方法
     * @param {*} _date 
     * @param {*} first 
     */
    getRili(_date, first) {
      let that = this;
      var date = null;
      if (_date != null && _date != undefined && _date != '') {
        date = new Date(_date);
      } else {
        date = new Date();
      }
      var nowDate = new Date();
      var today = date.getDay() == 0 ? '7' : date.getDay();
      var arr = new Array();
      console.log(today, 'today')
      for (var i = 1; i <= 7; ++i) {
        let key = FormatDateTime(ConvertDateTime(date).getTime() + ((-today + i) * 24 * 60 * 60 * 1000), "yyyy-MM-dd");
        var value = '';
        var checked = false;
        if (-today + i == 0) {
          if (first == 1) {
            value = '今天';
            checked = true;
          } else {
            value = FormatDateTime(ConvertDateTime(date).getTime() + ((-today + i) * 24 * 60 * 60 * 1000), "yyyy-MM-dd").split("-")[2];
          }
        } else {
          value = FormatDateTime(ConvertDateTime(date).getTime() + ((-today + i) * 24 * 60 * 60 * 1000), "yyyy-MM-dd").split("-")[2];
        }
        if (key == FormatDateTime(nowDate, "yyyy-MM-dd")) {
          value = '今天';
        }
        if (key == _date) {
          checked = true;
        }
        value = value.replace(/^0+/, '');
        var data = {
          "weekday": getWeeks(i),
          "key": key,
          "value": value,
          "isMy": true,
          "checked": checked,
        };
        arr.push(data);
      }
      this.setData({
        riliList: arr
      });
      var selectDays = new Array();
      var selectDay = "";
      for (var w = 0; w < arr.length; ++w) {
        if (arr[w].checked == true) {
          selectDays.push(arr[w].key);
          selectDay = arr[w].key;
        }
      }
      this.setData({
        selectedDay: selectDay,
        selectedDays: selectDays
      })
    },
    /**
     * @认证提示
     */
    handleVerify() {
      console.log('您还没有进行实名认证')
    },
    /**
     * @联系销售权限提示
     */
    handleTipsMsg() {
      this.setData({
        tipsMsg: true
      })
    }
  }
})